import TextWidget from './text-widget.js'
import {WIDGET_TYPE} from './widget-const.js';

const _template = Object.freeze({
    titles: ["name", "age", "addr."],
    records: [
        [
            "Jerry",
            34,
            "Nanjing",
        ],
        [
            "Nancy",
            25,
            "Beijing",
        ],
        [
            "CangJingkong",
            18,
            "Dongjing",
        ],
    ]
});

export default class TableWidget extends TextWidget {
    constructor(sectionData, dispatcher) {
        super(sectionData, dispatcher);
        try {
            this._data = JSON.stringify(this._sectionData.content ?? _template, null, 4);
        } catch (e) {
            this._data = JSON.stringify(_template, null, 4);
            console.error(e);
        }
    }
    get sectionData() {
        this._sectionData.type = WIDGET_TYPE.TABLE;
        this._sectionData.content = JSON.parse(this._data);
        return this._sectionData;
    }
    get language() {return 'json';}
    get textareaText() {return this._data;}
    set textareaText(value) {this._data = value;}
    Init() {
        super.Init();
        this._viewContainerElem.classList.add("scroll", "scroll-horizontal");
        this._editContainerElem.setAttribute('data-language', 'table');
        return this;
    }
    _UpdateView() {
        try {
            const _data = JSON.parse(this._data);
            const N = _data.titles.length;
            let _a = `<table class="table"> <thead><tr>`;
            for (let i = 0; i < N; ++i) {
                _a += `<th scope="col">${_data.titles[i]}</th>`;
            }
            _a += `</tr></thead><tbody>`;
            for (let i = 0, M = _data.records.length; i < M; ++i) {
                _a += `<tr>`;
                const _record = _data.records[i];
                for (let j = 0; j < N; ++j) {
                    _a += `<th>${_record[j]}</th>`;
                }
                _a += `</tr>`;
            }
            _a += `</tbody><table>`;
            this._viewContainerElem.innerHTML = _a;
        } catch (e) {
            this._viewContainerElem.innerText = e.message;
            console.log(e.stack);
        }
    }
}

